package com.yumeng.common.exception;

import com.yumeng.common.api.ApiCode;
import lombok.Getter;

import java.io.Serial;

/**
 * 基础异常
 * 所有自定义异常都集成于此，后期扩展
 * @author wxd
 * @date 2021/8/22 23:06
 */
@Getter
public abstract class BaseException extends RuntimeException{

    @Serial
    private static final long serialVersionUID = 1L;

    private ApiCode apiCode;
    private final String message;

    public BaseException(Throwable e) {
        super(e);
        this.message = e.getMessage();
    }

    public BaseException(String message, Object... args) {
        super(String.format(message, args));
        this.message = super.getMessage();
    }

    public BaseException(Throwable e, String message, Object... args) {
        super(String.format(message, args), e);
        this.message = super.getMessage();
    }

    public ApiCode getApiCode() {
        return apiCode != null ? apiCode : defaultApiCode();
    }

    //是否可以设置ApiCode，由子类决定
    protected RuntimeException setApiCode(ApiCode apiCode) {
        this.apiCode = apiCode;
        return this;
    }

    protected ApiCode defaultApiCode(){
        return ApiCode.ERROR;
    }

    public boolean hasCustomApiCode(){
        return false;
    }

    /**
     * 所属模块
     *//*
    private String module;
    *//**
     * 错误码
     *//*
    private String code;
    *//**
     * 错误码对应的参数
     *//*
    private Object[] args;
    *//**
     * 错误消息
     *//*
    private String defaultMessage;

    public BaseException(String module, String code, Object[] args, String defaultMessage) {
        this.module = module;
        this.code = code;
        this.args = args;
        this.defaultMessage = defaultMessage;
    }

    public BaseException(String module, String code, Object[] args) {
        this(module, code, args, null);
    }

    public BaseException(String module, String defaultMessage) {
        this(module, null, null, defaultMessage);
    }

    public BaseException(String code, Object[] args) {
        this(null, code, args, null);
    }

    public BaseException(String defaultMessage) {
        this(null, null, null, defaultMessage);
    }

    @Override
    public String getMessage() {
        String msg = null;
        String mod = StringUtils.isNotBlank(module) ? "模块："+ module : "";
        if (code != null) {
            msg = MessageUtils.getLocalMessage(code, args);
        } else if (msg == null) {
            msg = defaultMessage;
        }
        return mod + msg;
    }*/
}
